﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;

namespace DAL
{
    public class GroupMenuDal
    {
        private readonly AppDbContext _dbContext;

        public GroupMenuDal() { }
        // 通过依赖注入获取数据库上下文
        public GroupMenuDal(AppDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<GroupMenu> CreateAsync(GroupMenu groupMenu)
        {
            // 新增实体到数据库集
            _dbContext.groupManagers.Add(groupMenu);
            // 保存更改
            await _dbContext.SaveChangesAsync();
            return groupMenu;
        }

        public async Task<GroupMenu> GetByIdAsync(int groupId)
        {
            // 根据ID查询
            return await _dbContext.groupManagers.FirstOrDefaultAsync(g => g.GroupId == groupId);
        }

        public async Task<List<GroupMenu>> GetAllAsync()
        {
            // 查询所有并转换为列表
            return await _dbContext.groupManagers.ToListAsync();
        }

        public async Task UpdateAsync(GroupMenu groupMenu)
        {
            // 标记实体为修改状态
            _dbContext.groupManagers.Update(groupMenu);
            // 保存更改
            await _dbContext.SaveChangesAsync();
        }

        public async Task DeleteAsync(int groupId)
        {
            // 先查询实体
            var group = await GetByIdAsync(groupId);
            if (group != null)
            {
                // 移除实体
                _dbContext.groupManagers.Remove(group);
                // 保存更改
                await _dbContext.SaveChangesAsync();
            }
        }
    }
}
